package com.syqc.monitor.ui.carmonitor

import android.view.KeyEvent
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.UserConstant
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.hideSoftInput
import com.syqc.custom.SearchCarEditText
import com.syqc.entity.CarLick
import com.syqc.entity.CarTab
import com.syqc.maps.utils.BitmapUtil
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityCarMonitorBinding
import com.syqc.monitor.ui.alarm.CarReportFragment
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.VideoHostUtil
import com.syqc.videos.CarHistoryVideoFragment
import com.syqc.videos.CarMonitorViewModel
import com.syqc.videos.RealPlayerFragment

/** @Author Jasper @Time 2020/10/28 @Desc 单车监控 */
class CarMonitorActivity :
    BaseActivity<ActivityCarMonitorBinding>(ActivityCarMonitorBinding::inflate) {
    private var carRealVideo: RealPlayerFragment? = null
    private val mViewModel by viewModels<CarMonitorViewModel>()
    private var plate = ""

    override fun initView() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        immersionBar { titleBar(binding.llCarToolbar) }

        initFragment()
        initTab()
        initIntent()
        BitmapUtil.initLruCache()
        mViewModel.updateLauncher = registerResultOk { result ->
            if (result.resultCode == RESULT_OK) {
                val index = result.data?.getIntExtra(Keys.INTENT_OTHER, 0)
                mViewModel.photoUpdate.value = index
            }
        }
    }

    override fun setListener() {
        binding.tvChooseCar.filterFast {
            binding.editSearchCar.setText(plate)
            if (NetDataUtil.isSyncTree) {
                videoLauncher.launchAct<TeamsCarsActivity>(this) {
                    putExtra("VideoCar", true)
                }
            } else {
                videoLauncher.launchAct<ChooseCarActivity>(this) {
                    putExtra("VideoCar", true)
                }
            }

        }

        binding.editSearchCar.setOnCarIdBack(object : SearchCarEditText.OnCarIdBack {
            override fun back(entity: CarLick) {
                carRealVideo?.resetCar()
                mViewModel.carId.value = entity.carId
                mViewModel.videos.value = entity.videos
                mViewModel.carName.value = entity.carPlate
                CacheMMKV.encode("last_carId", entity.carId ?: "")
                plate = entity.carPlate
                hideSoftInput()
            }
        })
        binding.ivToolbarStart.setOnClickListener {
            if (isHome) {
                startHomeActivity()
            }
            finish()
        }
    }

    private val videoLauncher = registerResultOk { result ->
        carRealVideo?.resetCar()

        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID)
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME) ?: ""
            val videos = it.getStringExtra(Keys.VIDEO)
            mViewModel.carId.value = carId
            mViewModel.videos.value = videos
            mViewModel.carName.value = carName
            plate = carName
            binding.editSearchCar.setText(carName)
            CacheMMKV.encode("last_carId", carId ?: "")
        }
    }

    override fun onResume() {
        super.onResume()
        carMap.isResume = currentFragment is CarMapFragment
    }

    override fun onDestroy() {
        super.onDestroy()
        fragments.clear()
        currentFragment = null
        carRealVideo = null
        BitmapUtil.clearLruCache()
    }

    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID) ?: return
        VideoHostUtil.clearHostsClient()
        val carName = intent.getStringExtra(Keys.INTENT_PLATE) ?: ""
        val videos = intent.getStringExtra(Keys.INTENT_IS_VIDEO)
        binding.editSearchCar.postDelayed({
            plate = carName
            binding.editSearchCar.setText(carName)
            binding.editSearchCar.setEnable(false)
            binding.tvChooseCar.setTextColor(
                ContextCompat.getColor(
                    this,
                    R.color.color_999
                )
            )
            binding.tvChooseCar.isEnabled = false
            hideSoftInput()
            mViewModel.carId.value = carId
            mViewModel.carName.value = carName
            mViewModel.videos.value = videos
            binding.editSearchCar.isShowChoose = true
        }, 300)
    }

    private fun initTab() {
        val tabList = ArrayList<CarTab>()
        tabList.add(
            CarTab(R.string.desc_single_car_map, R.drawable.tab_item_one)
        )
        tabList.add(
            CarTab(R.string.desc_single_car_history_line, R.drawable.tab_item_two)
        )
        if (UserConstant.isRealVideo)
            tabList.add(
                CarTab(R.string.desc_single_car_real_video, R.drawable.tab_item_three)
            )
        if (UserConstant.isTapeVideo)
            tabList.add(
                CarTab(R.string.desc_single_car_history_video, R.drawable.tab_item_four)
            )
        tabList.add(
            CarTab(R.string.desc_single_car_report, R.drawable.tab_item_five)
        )

        binding.recyclerTab.layoutManager = GridLayoutManager(this, tabList.size)
        binding.recyclerTab.adapter = SingleTabAdapter().apply {
            setNewInstance(tabList)
            setOnItemClickListener { adapter, view, position ->
                carMap.isResume = position == 0
                showFragment(fragments[position])
                binding.editSearchCar.setText(plate)
                index = position
                notifyDataSetChanged()
            }
        }
    }

    private var fragments: ArrayList<Fragment> = ArrayList<Fragment>()
    private val carMap by lazy { CarMapFragment() }

    private fun initFragment() {
        if (carRealVideo != null) return
        fragments.add(carMap)
        fragments.add(CarHistoryLineFragment())
        if (UserConstant.isRealVideo) {
            carRealVideo = RealPlayerFragment()
            fragments.add(carRealVideo!!)
        }
        if (UserConstant.isTapeVideo) {
            fragments.add(CarHistoryVideoFragment())
        }
        fragments.add(CarReportFragment())
        carMap.isResume = true
        showFragment(carMap)
    }

    private var currentFragment: Fragment? = null

    /** 显示Fragment */
    private fun showFragment(fragment: Fragment) {
        if (currentFragment == fragment) return
        supportFragmentManager.beginTransaction().apply {
            if (currentFragment != null) hide(currentFragment!!)
            currentFragment = fragment
            if (fragment.isAdded) {
                show(fragment)
            } else {
                add(R.id.flCarContent, fragment).show(fragment)
            }
        }.commit()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (carRealVideo?.onKeyDown() == true) return false
        }
        return super.onKeyDown(keyCode, event)
    }

    class SingleTabAdapter :
        BaseQuickAdapter<CarTab, BaseViewHolder>(R.layout.item_tab_single_car) {
        var index: Int = 0
        override fun convert(holder: BaseViewHolder, item: CarTab) {
            item.run {
                val tvTabSingle = holder.getView<TextView>(R.id.tv_tab_single)
                val ivTabSingle = holder.getView<ImageView>(R.id.iv_tab_single)
                if (index == holder.layoutPosition) {
                    tvTabSingle.isSelected = true
                    ivTabSingle.isSelected = true
                } else {
                    tvTabSingle.isSelected = false
                    ivTabSingle.isSelected = false
                }
                tvTabSingle.setText(tabTitleId)
                ivTabSingle.setImageResource(tabImgId)
            }
        }
    }

}